import { Calendar, User, Tag, Eye, Heart } from "lucide-react";
import { Card, CardContent, CardFooter } from "./ui/card";
import { Badge } from "./ui/badge";
import { ImgProcess } from "@/utils/common";

export interface BlogPost {
  id: number;
  title: string;
  excerpt: string;
  content?: string; // 添加content属性，用于富文本内容
  author: string;
  date: string;
  category: string;
  tags: string[];
  image: string;
  readTime: string;
  viewCount: number;
  likeCount: number;
}

interface BlogCardProps {
  post: BlogPost;
  onClick: () => void;
}

// 提取纯文本内容并获取第一段
/**
 * 针对中文富文本优化的提取函数
 * @param html 富文本字符串
 * @param maxLength 最大长度，默认150字符（中文环境下）
 * @returns 处理后的纯文本第一段
 */
const extractChineseRichText = (html: string, maxLength: number = 150): string => {
  if (!html) return '';

  try {
    // 1. 移除所有HTML标签，但保留段落信息
    let text = html
      .replace(/<br\s*\/?>/gi, '\n') // 保留换行
      .replace(/<\/p>|<\/div>/gi, '\n') // 段落结束换行
      .replace(/<[^>]*>/g, '') // 移除其他标签
      .replace(/&nbsp;/g, ' ')
      .replace(/&[^;]+;/g, ' '); // 处理其他HTML实体

    // 2. 合并多余的空白字符
    text = text.replace(/\s+/g, ' ').replace(/\n\s*/g, '\n').trim();
    
    // 3. 按换行符分割段落，获取第一段
    const paragraphs = text.split('\n').filter(p => p.trim().length > 0);
    const firstParagraph = paragraphs[0]?.trim() || '';
    
    if (!firstParagraph) return '';
    
    // 4. 中文环境下，按句号分割更自然
    const chineseSentences = firstParagraph.split(/[。！？\.!?]/);
    const firstSentence = chineseSentences[0]?.trim() || firstParagraph;
    
    // 5. 截断处理
    if (firstSentence.length <= maxLength) {
      return firstSentence;
    }
    
    return firstSentence.substring(0, maxLength) + '...';
    
  } catch (error) {
    console.error('提取中文富文本失败:', error);
    return html.replace(/<[^>]*>/g, '').substring(0, maxLength);
  }
};

export default function BlogCard({
  post,
  onClick,
}: BlogCardProps) {
  // 优先使用content字段的内容，如果没有则使用excerpt
  const displayContent = post.excerpt ? extractChineseRichText(post.excerpt) : post.excerpt;
  
  return (
    <Card
      className="overflow-hidden cursor-pointer transition-all hover:shadow-lg hover:-translate-y-1"
      onClick={onClick}
    >
      <div className="aspect-video overflow-hidden">
        <img
          src={ImgProcess(post.image)}
          alt={post.title}
          className="w-full h-full object-cover transition-transform hover:scale-105"
        />
      </div>
      <CardContent className="p-6">
        <div className="flex items-center gap-2 mb-3">
          <Badge variant="secondary">{post.category}</Badge>
          <span className="text-gray-500 text-sm">
            {post.readTime}
          </span>
        </div>
        <h3 className="mb-3 text-gray-900 line-clamp-2">
          {post.title}
        </h3>
        <p className="text-gray-600 text-sm line-clamp-3 mb-4">
          {displayContent}
        </p>
        <div className="flex flex-wrap gap-2 mb-4">
          {post.tags.map((tag) => (
            <div
              key={tag}
              className="flex items-center gap-1 text-xs text-gray-500"
            >
              <Tag className="w-3 h-3" />
              {tag}
            </div>
          ))}
        </div>
      </CardContent>
      <CardFooter className="px-6 pb-6 pt-0 flex items-center justify-between text-sm text-gray-500">
        <div className="flex items-center gap-4">
          <div className="flex items-center gap-1">
            <User className="w-4 h-4" />
            {post.author}
          </div>
          <div className="flex items-center gap-1">
            <Calendar className="w-4 h-4" />
            {post.date}
          </div>
        </div>
        <div className="flex items-center gap-4">
          <div className="flex items-center gap-1">
            <Eye className="w-4 h-4" />
            {post.viewCount}
          </div>
          <div className="flex items-center gap-1">
            <Heart className="w-4 h-4" />
            {post.likeCount}
          </div>
        </div>
      </CardFooter>
    </Card>
  );
}